//
//  ST_DailyMomentItemView.swift
//  btvideo
//
//  Created by mac on 2020/7/21.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SDWebImage
import SwiftyUserDefaults

class ST_DailyMomentItemView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        
        self.addSubview(avatar_image_view)
        avatar_image_view.snp.makeConstraints { (make) in
            make.width.height.equalTo(44)
            make.top.equalToSuperview().offset(18)
            make.left.equalToSuperview().offset(15)
        }
        
        self.addSubview(icon_supplement_image_view)
        icon_supplement_image_view.snp.makeConstraints { (make) in
            make.center.equalTo(avatar_image_view)
            make.width.height.equalTo(60)
        }
        
        self.addSubview(username_label)
        username_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(69)
            make.top.equalToSuperview().offset(20)
            make.height.equalTo(22)
        }
        self.addSubview(time_label)
        time_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(69)
            make.top.equalTo(username_label.snp.bottom).offset(1)
            make.height.equalTo(17)
        }
        
        
        self.addSubview(signView)
        signView.snp.makeConstraints { (make) in
            make.height.equalTo(18)
            make.width.equalTo(70)
            make.centerY.equalTo(username_label)
            make.left.equalTo(username_label.snp.right).offset(4)
        }
        
        self.addSubview(imageContainer)
        imageContainer.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(70)
            make.left.equalToSuperview().offset(69)
            make.size.equalTo(CGSize.zero)
        }
        
        self.addSubview(dailySignView)
        dailySignView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(30)
            make.left.equalToSuperview().offset(69)
            make.height.equalTo(ST_DailyMomentSignView.height)
        }
        
        self.addSubview(content_label)
        content_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(69)
            make.right.equalToSuperview().offset(-15)
            make.top.equalToSuperview().offset(30)
            make.size.equalTo(CGSize.zero)
        }
        
        self.addSubview(comment_btn)
        comment_btn.snp.makeConstraints { (make) in
            make.height.equalTo(44)
            make.right.equalToSuperview().offset(-15)
            make.bottom.equalToSuperview()
        }
        
        self.addSubview(thumbUpBtn)
        thumbUpBtn.snp.makeConstraints { (make) in
            make.right.equalTo(comment_btn.snp.left).offset(-20)
            make.height.centerY.equalTo(comment_btn)
        }
        
        self.addSubview(watchedNumberBtn)
        watchedNumberBtn.snp.makeConstraints { (make) in
            make.right.equalTo(thumbUpBtn.snp.left).offset(-20)
            make.height.centerY.equalTo(comment_btn)
        }
        
        self.addSubview(more_button)
                
        let moreButtonW = 17.cgFloat
        
        more_button.snp.makeConstraints { (make) in
            make.centerY.equalTo(avatar_image_view)
            make.right.equalToSuperview().offset(-15+(44-moreButtonW)/2.0)
            make.width.height.equalTo(44)
        }
        
        
        self.addSubview(sameCityLabel)
        sameCityLabel.snp.makeConstraints { (make) in
            make.left.equalTo(content_label)
            make.height.equalTo(20)
            make.centerY.equalTo(comment_btn)
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
//    MARK: - Properties
    fileprivate lazy var avatar_image_view:UIImageView = {
       let control = UIImageView()
        control.contentMode = .scaleAspectFill
        control.cornerRadius = 44/2.0
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(push_user_center_handle))
        control.isUserInteractionEnabled = true
        control.addGestureRecognizer(tap)
        return control
    }()
    
    fileprivate lazy var icon_supplement_image_view:UIImageView = {
        let control = UIImageView()
       control.contentMode = UIView.ContentMode.scaleAspectFill
       return control
    }()
    
    fileprivate lazy var signView:ST_UserSignView = {
        let control = ST_UserSignView()
       return control
    }()
    
    fileprivate lazy var username_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = UIColor.init(hexString: "#333333")
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        return control
    }()
    
    fileprivate lazy var time_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = UIColor.init(hexString: "#ACB4C0")
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
        return control
    }()
    
    
    fileprivate lazy var imageContainer:ST_DailyMomentImageContainer = {
        let control = ST_DailyMomentImageContainer()
        return control
    }()
    
    fileprivate lazy var dailySignView:ST_DailyMomentSignView = {
        let control = ST_DailyMomentSignView()
        control.addTarget(self, action: #selector(pushSomeDailyHandle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var content_label:YYLabel = {
        let control = YYLabel()
//        control.backgroundColor = .random
        control.numberOfLines = 0
        
        let unfoldActionStr = NSMutableAttributedString.init(string: "...展开")
            
        let hi = YYTextHighlight()
        
        let action:YYTextAction = {[weak self] containerView, text, range, rect in
            
            guard let fold = self?.model?.isFoldContent else{
                return
            }
            
            self?.model?.isFoldContent = !fold
            
            self?.reload_cell_closure?()
        }
        
        hi.tapAction = action
        
        unfoldActionStr.yy_setColor(UIColor.init(hex: 0x42CEDA), range: NSRange.init(location: 3, length: 2))
        
        unfoldActionStr.yy_setTextHighlight(hi, range: NSRange.init(location: 3, length: 2))
       
        unfoldActionStr.yy_font = UIFont.systemFont(ofSize: 15)
            
            let seeMore = YYLabel()
            seeMore.attributedText = unfoldActionStr
            seeMore.sizeToFit()
            
        let truncationToken = NSAttributedString.yy_attachmentString(withContent: seeMore, contentMode: UIView.ContentMode.center, attachmentSize: seeMore.size, alignTo: UIFont.systemFont(ofSize: 15), alignment: YYTextVerticalAlignment.center)
        
        truncationToken.yy_setBaselineOffset(-2, range: NSRange.init(location: 0, length: truncationToken.length))
        
        control.truncationToken = truncationToken
        
        return control
    }()
    
    fileprivate lazy var thumbUpBtn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImage(ST_ImageUtils.imageName("thumb_up_mid_normal"), for: UIControl.State.normal)
        control.setImage(ST_ImageUtils.imageName("thumb_up_mid_selected"), for: UIControl.State.selected)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        control.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 0)
        control.contentHorizontalAlignment = .left
        control.setTitleColorForAllStates(UIColor.init(hex: 0xACB4C0)!)
        control.addTarget(self, action: #selector(thumb_up_click_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    var comment_click_closure:(()->())?
    
    fileprivate lazy var comment_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImage(ST_ImageUtils.imageName("comment_icon"), for: UIControl.State.normal)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        control.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 0)
        control.contentHorizontalAlignment = .left
        control.setTitleColorForAllStates(UIColor.init(hex: 0xACB4C0)!)
        control.addTarget(self, action: #selector(commentClickHandle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var more_button:UIButton = {
            let control = UIButton.init(type: UIButton.ButtonType.custom)
            control.setImageForAllStates(ST_ImageUtils.imageName("首页_icon_更多操作")!)
            control.add_touch_up(insideTarget: self, action: #selector(more_btn_click_handle))
    //        control.backgroundColor = Color.random
            return control
        }()
    
    fileprivate lazy var watchedNumberBtn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImage(ST_ImageUtils.imageName("watched_num_icon"), for: UIControl.State.normal)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        control.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 0)
        control.contentHorizontalAlignment = .left
        control.setTitleColorForAllStates(UIColor.init(hex: 0xACB4C0)!)
        control.alpha = 0
//        control.addTarget(self, action: #selector(thumb_up_click_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var sameCityLabel = CityDistanceControl()
    
    var displayWatchedBtn = false{
        didSet{
            watchedNumberBtn.alpha = displayWatchedBtn ? 1 : 0
        }
    }
    
    var reload_cell_closure:(()->())?
//    MARK: - Bind Model
    weak var model:DailyMomentOfHallModel?{
        didSet{
            
            guard let m = model else{
                return
            }
            
            model?.foldClosure = {[weak self] in
                self?.reload_cell_closure?()
            }
            
            avatar_image_view.sd_setImage(with: m.avatar.compress_image().url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image(), options: SDWebImageOptions(), context: nil)
            
            icon_supplement_image_view.pin_setImage(from: AVATAR_SUPPLEMENT(guardTime: m.guardTime, guardContent: m.guardContent)?.url)
            
            
            username_label.text = m.nickname
            
            time_label.text = m.createStr
            
            signView.bind_data(isVip: m.isVip, detectedFace: m.detectedFace)
            
            imageContainer.snp.updateConstraints { (make) in
                make.size.equalTo(m.mediaSize)
            }
            
            imageContainer.imagesArray = m.contentImages
            
            dailySignView.bind(text: m.name, url: m.image)
            
            dailySignView.snp.updateConstraints { (make) in
                make.top.equalToSuperview().offset(m.signTopConstraint)
            }
            
            content_label.attributedText = m.contetnAttriStr
            
            content_label.snp.updateConstraints { (make) in
                make.top.equalToSuperview().offset(m.contentTopConstraint)
                if m.isFoldContent{
                    make.size.equalTo(m.foldContentSize)
                }else{
                    make.size.equalTo(m.unfoldContentSize)
                }
            }
            
            thumbUpBtn.isSelected = m.isThumbUp
            
            thumbUpBtn.setTitleForAllStates(m.thumpCount.st_number_description() + "  ")
                
            comment_btn.setTitleForAllStates(m.commentCount.st_number_description() + "  ")
            
            watchedNumberBtn.setTitleForAllStates(m.viewCount.st_number_description() + "  ")
            
            
            if let city = m.cityName,city.count > 0,let distance = m.distance{
                self.sameCityLabel.label.text = city + " " + distance
                self.sameCityLabel.isHidden = false
            }else{
                self.sameCityLabel.isHidden = true
            }
            
        }
    }
    
}



extension ST_DailyMomentItemView{
    
    
    @objc fileprivate func pushSomeDailyHandle(){
        
        
        let vc = ST_SomeOneDailyViewController()
        vc.dailyModel = self.model?.conver_to_daily_base_model()
        self.parentViewController?.navigationController?.pushViewController(vc)
    }
    
    @objc func ban_current_user_handle(){
        
        guard let m = model else{
            return
        }
        
        BAN_SOMEBODY_HANDLE(userId: m.accid, close_view: false, hud_controller: self.parentViewController)
        
    }
    
    fileprivate func deleteAlert(id:String){
        
        JVrequest(PH.deleteDailyApi,parameters: ["daily_content_id":id],success: { (json) in
            
            NotificationCenter.default.post(name: Notification.Name.DelDaily, object: nil, userInfo: ["id":id])
            
        }) { (code, err) in
            
            self.parentViewController?.toast(text: err)
        }
        
    }
    
    @objc fileprivate func commentClickHandle(){
        self.comment_click_closure?()
    }
    
    @objc fileprivate func more_btn_click_handle(){
        
        let vc = ST_BTSheetActionController.init(title: nil, message: nil)
        
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium),.foregroundColor: UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)]
        
//        是自己 只有删除
        if self.model?.accid == Defaults[.currentUserID]{
            
            
            let str2 = NSMutableAttributedString.init(string: "删除")
            
            str2.addAttributes(attr, range: NSRange(location: 0, length: str2.length))
            
            vc.addAction(ST_BTAlertAction.init(title: str2, handler: {[weak self] (action) in
                
                guard let m = self?.model else{
                    return
                }
                
                PlayFeedBack()
                
                let attrString = NSMutableAttributedString(string: "确认要删除此日常吗？")
                
                let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.medium),.foregroundColor: UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)]
                attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
                
                let messageAttrString = NSMutableAttributedString(string: "删除后点赞和评论会被清空")
                
                let attr2: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.38, green: 0.4, blue: 0.44, alpha: 1)]
                
                messageAttrString.addAttributes(attr2, range: NSRange(location: 0, length: messageAttrString.length))
                
                let alert = ST_BTAlertViewController.init(title: attrString, message: messageAttrString, imageName: "首页_icon_提示", confirmText: " 确定删除", cancelText: "再想想看")
                
                alert.overCurrentContext = true
                
                alert.over_current_context_alpha = "0.4"
                
                alert.confirm_closure = {[weak self] in
                    
                    self?.deleteAlert(id: m.id.string)
                    
                }
                
                GlobalPresent(toController: alert, animated: false)
                
                
                
            }))
            
            
            vc.show()
            
            return
        }
        
        if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .male || Defaults[.isPanda] {
        
        let str2 = NSMutableAttributedString.init(string: "拉黑")
        
        str2.addAttributes(attr, range: NSRange(location: 0, length: str2.length))
        
        vc.addAction(ST_BTAlertAction.init(title: str2, handler: {[weak self] (action) in
           
            self?.ban_current_user_handle()
            
        }))
        
        }
        
        let str3 = NSMutableAttributedString.init(string: "举报")
        
        str3.addAttributes(attr, range: NSRange(location: 0, length: str3.length))
        
        vc.addAction(ST_BTAlertAction.init(title: str3, handler: { (action) in
           
            let vc = ST_ReportPersonController()
            vc.userId = self.model?.accid ?? ""
            let nav = UINavigationController.create_hiding_bar_navigation_controller(rootViewController: vc)
            GlobalPresent(toController: nav)
            
        }))
        
        vc.show()
        
    }
    
    @objc fileprivate func thumb_up_click_handle(){
        
        guard let m = self.model else { return  }
        
        if BTVerticalAlertViewController.toastBindPhoneRequireAlert(fromController: self.parentViewController) {
            return
        }
        
        if m.accid == ST_BTUserInfoManager.shared.current_account_info?.accid{
            
            let thumbUpHud = ST_BTHUDController.init(noticeText: "不能给自己点赞哦")
            
            GlobalPresent(toController: thumbUpHud, animated: false)
            
            main_thread_execute(afterDelay: 2.5) {
                thumbUpHud.dismiss(animated: false, completion: nil)
            }
            
            return
        }
        
        self.thumbUpBtn.isUserInteractionEnabled = false
        
        let api = self.thumbUpBtn.isSelected ? PH.un_thumbUpDailyApi : PH.thumbUpDailyApi
        
        PlayFeedBack()
        
        self.thumbUpBtn.isSelected = !self.thumbUpBtn.isSelected
        
        self.model?.isThumbUp = !m.isThumbUp
        if self.thumbUpBtn.isSelected{
            self.model?.thumpCount += 1
        }else{
            self.model?.thumpCount -= 1
        }
        
        let str = (self.model?.thumpCount ?? 0).st_number_description() + "  "
        
        self.thumbUpBtn.setTitleForAllStates(str)
        
        if api == PH.thumbUpDailyApi{
            
            ST_BTGlobalDataCenter.shared.thumbUpDailyEvent(dailyType: m.name, liked_user_id: m.accid, daily_id: m.dailyId.string)
            
        }
        
        
        JVrequest(api,parameters: ["target_accid":m.accid,"daily_content_id":m.id.string], success: { (json) in
            
            self.thumbUpBtn.isUserInteractionEnabled = true
           
            NotificationCenter.default.post(name: Notification.Name.thumbUpDaily, object: nil, userInfo: ["fromController":self.parentViewController ?? 0,"isThumbUp":self.thumbUpBtn.isSelected,"id":m.id.string])
            
        }) { (code, err) in
            
            self.thumbUpBtn.isUserInteractionEnabled = true
            
            self.parentViewController?.toast(text: err)
        }
        
    }
    
    @objc fileprivate func push_user_center_handle(){
        
        guard let m = model else{
            return
        }
        
        let vc = ST_PairsCenterViewController()
        
        vc.accid = m.accid

        let nav = PairsCenterInteractiveNavigationController.init(rootViewController: vc)
        
        nav.overCurrentContext = true
        
        GlobalPresent(toController: nav)
        
    }
}








//MARK: -

class CityDistanceControl: UIControl {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.addSubview(icon_image_view)
        icon_image_view.snp.makeConstraints { (make) in
            make.centerY.left.equalToSuperview()
            make.width.height.equalTo(20)
        }
        
        self.addSubview(label)
        label.snp.makeConstraints { (make) in
            make.centerY.right.equalToSuperview()
            make.left.equalTo(icon_image_view.snp.right).offset(3)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate lazy var icon_image_view:UIImageView = {
        let control = UIImageView.init(image: ST_ImageUtils.imageName("daily_loc_icon"))
        return control
    }()
    
    lazy var label:UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium)
        label.textColor = UIColor(red: 1, green: 0.77, blue: 0.03, alpha: 1)
        
        return label
    }()
    
    
}
